package com.wtzz.police.base.controller;
/**
 * 鉴权Controller
 */
import com.wtzz.police.base.bean.req.LoginDto;
import com.wtzz.police.base.model.enums.WtzzResponse;
import com.wtzz.police.base.model.response.JwtAuthenticationResponse;
import com.wtzz.police.base.model.response.ResponseBean;
import com.wtzz.police.base.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api(tags = "系统验证")
@Controller
@RequestMapping("auth")
@Slf4j
@Validated
public class AuthController {

    @Autowired
    private AuthService authService;

    @ResponseBody
    @PostMapping("login")
    @ApiOperation(value = "登录", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean<JwtAuthenticationResponse> login(
            @RequestBody
            @ApiParam(value = "账户信息", type = "body")
            @Validated
                    LoginDto loginDto) {
        return ResponseBean.of(authService.login(loginDto.getUsername(), loginDto.getPassword()));
    }

    @ApiOperation("退出")
    @GetMapping("logout")
    @ResponseBody
    public ResponseBean<JwtAuthenticationResponse> logout() {
        log.info("退出系统");
        SecurityContextHolder.getContext().setAuthentication(null);
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @ApiOperation(value = "刷新token(需要旧的token还没过期)")
    @GetMapping("refresh")
    @ResponseBody
    public ResponseBean<JwtAuthenticationResponse> refresh(
            @RequestHeader(value = "Authorization")
                    String token) {
        return ResponseBean.of(authService.refresh(token));
    }

}